package com.ruoyi.project.zerocarbon.service.impl;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.QiniuUtils;
import com.ruoyi.project.zerocarbon.domain.*;
import com.ruoyi.project.zerocarbon.mapper.*;
import com.ruoyi.project.zerocarbon.service.IDeclarationZhejiangService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.utils.file.QiniuUtils.getQiniuPath;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-03-13
 */
@Slf4j
@Service
public class DeclarationZhejiangServiceImpl implements IDeclarationZhejiangService 
{
    @Autowired
    private DeclarationZhejiangMapper declarationZhejiangMapper;
    @Autowired
    private DeclareExternalOrganizationMapper declareExternalOrganizationMapper;
    @Autowired
    private DeclareFundsMapper declareFundsMapper;
    @Autowired
    private DeclareMediaCoverageMapper declareMediaCoverageMapper;
    @Autowired
    private DeclareImplementationPlanMapper declareImplementationPlanMapper;
    @Autowired
    private DeclareFileMapper declareFileMapper;
    @Resource
    private QiniuUtils qiniuUtils;
    @Autowired
    private DeclareJudgeMapper declareJudgeMapper;
    @Autowired
    private DeclareRankingMapper declareRankingMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public DeclarationZhejiang selectDeclarationZhejiangById(Long id)
    {
        return declarationZhejiangMapper.selectDeclarationZhejiangById(id);
    }

    @Override
    public DeclarationZhejiang selectDeclarationZhejiangByUserName(String userName) {
        DeclarationZhejiang declarationCheck = new DeclarationZhejiang();
        declarationCheck.setUserName(userName);
        DeclarationZhejiang declarationZhejiang = declarationZhejiangMapper.selectDeclarationZhejiangListByUserName(userName);
        if (declarationZhejiang != null){
            declarationZhejiang.setExternalOrganizations(declareExternalOrganizationMapper.selectDeclareExternalOrganizationByDeclarationId(declarationZhejiang.getId()));
            declarationZhejiang.setFunds(declareFundsMapper.selectDeclareFundsByDeclarationId(declarationZhejiang.getId()));
            declarationZhejiang.setImplementationPlans(declareImplementationPlanMapper.selectDeclareImplementationPlanByDeclarationId(declarationZhejiang.getId()));
            declarationZhejiang.setMediaCoverages(declareMediaCoverageMapper.selectDeclareMediaCoverageByDeclarationId(declarationZhejiang.getId()));
            return declarationZhejiang;
        }else {
            return null;
        }
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param declarationZhejiang 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<DeclarationZhejiang> selectDeclarationZhejiangList(DeclarationZhejiang declarationZhejiang)
    {
        return declarationZhejiangMapper.selectDeclarationZhejiangList(declarationZhejiang);
    }

    @Override
    public List<DeclarationZhejiang> selectDeclarationZhejiangListExport(DeclarationZhejiang declarationZhejiang)
    {
        return declarationZhejiangMapper.selectDeclarationZhejiangListExport(declarationZhejiang);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param declarationZhejiang 【请填写功能名称】
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDeclarationZhejiang(DeclarationZhejiang declarationZhejiang)
    {
        if (declarationZhejiang.getSaveType() != null && declarationZhejiang.getSaveType() != 0){
            String maxSerial = declarationZhejiangMapper.selectMaxSerial();
            if (StringUtils.isEmpty(maxSerial) || Integer.valueOf(maxSerial) == 0){
                declarationZhejiang.setRegionSerial("000001");
            }else {
                declarationZhejiang.setRegionSerial(NumberUtils.buildSerial(Integer.valueOf(maxSerial)));
            }
        }
        DeclarationZhejiang declarationCheck = new DeclarationZhejiang();
        declarationCheck.setUserName(declarationZhejiang.getUserName());
        List<DeclarationZhejiang> declarationHistoryList = declarationZhejiangMapper.selectDeclarationZhejiangList(declarationCheck);
        int saveSuccess = 0;
        if (CollectionUtils.isNotEmpty(declarationHistoryList)){
            saveSuccess = 1;
            DeclarationZhejiang declarationHistory = declarationHistoryList.get(0);
            if (declarationHistory.getSaveType() != null && declarationHistory.getSaveType() ==1){
                throw new CustomException("申报已经提交，不可修改");
            }
            declarationZhejiang.setId(declarationHistory.getId());
            declarationZhejiang.setUpdateTime(DateUtils.getNowDate());
            declarationZhejiang.setAuditStatus(11);
            declarationZhejiangMapper.updateDeclarationZhejiang(declarationZhejiang);
            //更新
            declareExternalOrganizationMapper.deleteDeclareExternalOrganizationByDeclarationId(declarationHistory.getId());
            declareFundsMapper.deleteDeclareFundsByDeclarationId(declarationHistory.getId());
            declareImplementationPlanMapper.deleteDeclareImplementationPlanByDeclarationId(declarationHistory.getId());
            declareMediaCoverageMapper.deleteDeclareMediaCoverageByDeclarationId(declarationHistory.getId());
        }else {
            declarationZhejiang.setCreateTime(DateUtils.getNowDate());
            declarationZhejiang.setAuditStatus(11);
            saveSuccess = declarationZhejiangMapper.insertDeclarationZhejiang(declarationZhejiang);
        }
        if (saveSuccess > 0){
            Long declarationId = declarationZhejiang.getId();
            if (!CollectionUtils.isEmpty(declarationZhejiang.getExternalOrganizations())){
                for (int i = 0; i < declarationZhejiang.getExternalOrganizations().size(); i++) {
                    DeclareExternalOrganization declareExternalOrganization = declarationZhejiang.getExternalOrganizations().get(i);
                    declareExternalOrganization.setDeclarationId(declarationId);
                    declareExternalOrganizationMapper.insertDeclareExternalOrganization(declareExternalOrganization);
                }
            }
            if (!CollectionUtils.isEmpty(declarationZhejiang.getFunds())){
                for (int i = 0; i < declarationZhejiang.getFunds().size(); i++) {
                    DeclareFunds declareFunds = declarationZhejiang.getFunds().get(i);
                    declareFunds.setDeclarationId(declarationId);
                    declareFundsMapper.insertDeclareFunds(declareFunds);
                }
            }
            if (!CollectionUtils.isEmpty(declarationZhejiang.getImplementationPlans())){
                for (int i = 0; i < declarationZhejiang.getImplementationPlans().size(); i++) {
                    DeclareImplementationPlan declareImplementationPlan = declarationZhejiang.getImplementationPlans().get(i);
                    declareImplementationPlan.setDeclarationId(declarationId);
                    declareImplementationPlanMapper.insertDeclareImplementationPlan(declareImplementationPlan);
                }
            }
            if (!CollectionUtils.isEmpty(declarationZhejiang.getMediaCoverages())){
                for (int i = 0; i < declarationZhejiang.getMediaCoverages().size(); i++) {
                    DeclareMediaCoverage declareMediaCoverage = declarationZhejiang.getMediaCoverages().get(i);
                    declareMediaCoverage.setDeclarationId(declarationId);
                    declareMediaCoverageMapper.insertDeclareMediaCoverage(declareMediaCoverage);
                }
            }
            if (declarationZhejiang.getSaveType() != null && declarationZhejiang.getSaveType() ==1){
                if(StringUtils.isEmpty(declarationZhejiang.getSupplementaryMaterialsPath()) && StringUtils.isEmpty(declarationZhejiang.getVideoPath())){
                    return saveSuccess;
                }
                //打包zip
                String zipPath = "declaration/zip/"+declarationZhejiang.getHeadName().trim() + "-" + declarationZhejiang.getRegionSerial() + ".zip";
                List<String> collect = new ArrayList<>();
                if(StringUtils.isNotEmpty(declarationZhejiang.getVideoPath())){
                    collect.add(declarationZhejiang.getVideoPath());
                }
                if(StringUtils.isNotEmpty(declarationZhejiang.getSupplementaryMaterialsPath())){
                    collect.add(declarationZhejiang.getSupplementaryMaterialsPath());
                }
                String zipid = qiniuUtils.zipFiles(collect,zipPath);
                DeclarationZhejiang declarationZhejiangFile = new DeclarationZhejiang();
                declarationZhejiangFile.setId(declarationId);
                declarationZhejiangFile.setQiniuzipid(zipid);
                declarationZhejiangFile.setQiniuzippath(getQiniuPath(zipPath));
                log.info("打包zip QiniuPath: {},zipid:{}",declarationZhejiangFile.getQiniuzippath(),zipid);
                declarationZhejiangMapper.updateDeclarationZhejiang(declarationZhejiangFile);
            }
        }
        return saveSuccess;
    }

    public static void main(String[] args) {
        System.out.println(Integer.valueOf("000001"));
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param declarationZhejiang 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateDeclarationZhejiang(DeclarationZhejiang declarationZhejiang)
    {
        declarationZhejiang.setUpdateTime(DateUtils.getNowDate());
        return declarationZhejiangMapper.updateDeclarationZhejiang(declarationZhejiang);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteDeclarationZhejiangByIds(Long[] ids)
    {
        return declarationZhejiangMapper.deleteDeclarationZhejiangByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteDeclarationZhejiangById(Long id)
    {
        return declarationZhejiangMapper.deleteDeclarationZhejiangById(id);
    }

    @Override
    public List<DeclarationZhejiang> getJudgeDecorationListByVoList(List<DeclarationZhejiang> groupDecorationList,Integer judgeStatus,String expertNumber) {
        List<DeclarationZhejiang> list = new ArrayList<>();
        for (DeclarationZhejiang declaration:groupDecorationList){
            DeclareJudge declareJudge = new DeclareJudge();
            declareJudge.setDeclarationId(declaration.getId());
            declareJudge.setExpertNumber(expertNumber);
            if (judgeStatus != null){
                declareJudge.setStatus(judgeStatus);
            }
            List<DeclareJudge> declareJudges = declareJudgeMapper.selectDeclareJudgeList(declareJudge);
            if (CollectionUtils.isNotEmpty(declareJudges)){
                declaration.setScore(declareJudges.get(0).getScore());
                declaration.setJudgeStatus(declareJudges.get(0).getStatus());
            }else {
                //                if (judgeStatus != null && judgeStatus == 0){
                //                    continue;
                //                }
                declaration.setJudgeStatus(0);
            }
            // 推荐星级
            DeclareRanking declareRanking = declareRankingMapper.selectDeclareRankingByDeclarationId(declaration.getId());
            Integer score = 0;
            if (declareRanking != null){
                score = declareRanking.getScore();
            }
            int ranking = declarationZhejiangMapper.getRankingNum(score) + 1;
            declaration.setRanking(ranking);
            list.add(declaration);
        }
        return list;
    }

    @Override
    public List<DeclarationZhejiang> getRankingDecorationList(DeclarationZhejiang declarationZhejiang) {
        List<DeclarationZhejiang> rankingDecorationList = declarationZhejiangMapper.getRankingDecorationList(declarationZhejiang);
        for (DeclarationZhejiang declaration:rankingDecorationList){
            List<DeclareJudge> declareJudges = declareJudgeMapper.selectDeclareJudgeByDecorationId(declaration.getId());
            declaration.setDeclareJudges(declareJudges);
            if (!CollectionUtils.isEmpty(declareJudges)){
//                if (declareJudges.size() < 2){
//                    declaration.setScore(0);
//                }else if (declareJudges.size() == 3){
//                    Integer sum = declareJudges.stream().mapToInt(DeclareJudge::getScore).sum();
//                    declaration.setScore(Math.round(sum/3));
//                }else if (declareJudges.size() == 2){
//                    Integer sum = declareJudges.stream().mapToInt(DeclareJudge::getScore).sum();
//                    declaration.setScore(Math.round(sum/3));
//                }
                Integer sum = declareJudges.stream().mapToInt(DeclareJudge::getScore).sum();
                declaration.setScore(Math.round(sum/3));
            }else {
                declaration.setScore(0);
            }
            DeclareRanking declareRanking = declareRankingMapper.selectDeclareRankingByDeclarationId(declaration.getId());
            Integer score = 0;
            if (declareRanking != null){
                score = declareRanking.getScore();
            }
            int ranking = declarationZhejiangMapper.getRankingNum(score) + 1;
            declaration.setRanking(ranking);
        }
        return rankingDecorationList;
    }
}
